// admin.js
const app = getApp()
const { API } = require('../../utils/api')

Page({
  data: {
    userInfo: null,
    todayStats: {
      totalSales: '0.00',
      totalVolume: '0.00',
      orderCount: 0
    },
    loading: false
  },

  onLoad() {
    // 检查管理员权限
    if (!app.globalData.userInfo || app.globalData.userInfo.role !== 'admin') {
      wx.showModal({
        title: '权限不足',
        content: '您没有管理员权限',
        showCancel: false,
        success: () => {
          wx.navigateBack()
        }
      })
      return
    }

    this.setData({
      userInfo: app.globalData.userInfo
    })
    
    this.loadTodayStats()
  },

  onShow() {
    // 页面显示时刷新今日统计数据
    this.loadTodayStats()
  },

  async loadTodayStats() {
    this.setData({ loading: true })
    
    try {
      // 获取今日日期
      const today = new Date().toISOString().split('T')[0] // YYYY-MM-DD格式
      
      // 调用后端API获取今日销售报表
      const response = await API.admin.getSalesReport({
        startDate: today,
        endDate: today
      })
      
      if (response && response.length > 0) {
        const todayReport = response[0]
        this.setData({
          todayStats: {
            totalSales: todayReport.totalAmount.toFixed(2),
            totalVolume: todayReport.totalVolume.toFixed(2),
            orderCount: todayReport.totalOrders
          }
        })
      } else {
        // 没有今日数据，显示0
        this.setData({
          todayStats: {
            totalSales: '0.00',
            totalVolume: '0.00',
            orderCount: 0
          }
        })
      }
    } catch (error) {
      console.error('获取今日统计失败:', error)
      // 如果API调用失败，回退到本地存储方式
      this.loadTodayStatsFromLocal()
    } finally {
      this.setData({ loading: false })
    }
  },

  loadTodayStatsFromLocal() {
    // 从本地存储获取今日统计数据（回退方案）
    const records = wx.getStorageSync('fuelRecords') || []
    const today = new Date().toDateString()
    
    const todayRecords = records.filter((record) => {
      const recordDate = new Date(record.date).toDateString()
      return recordDate === today
    })

    let totalSales = 0
    let totalVolume = 0
    
    todayRecords.forEach((record) => {
      totalSales += record.amount
      totalVolume += record.volume
    })

    this.setData({
      todayStats: {
        totalSales: totalSales.toFixed(2),
        totalVolume: totalVolume.toFixed(2),
        orderCount: todayRecords.length
      }
    })
  },

  goToPriceManage() {
    wx.navigateTo({
      url: '/pages/admin/price/price'
    })
  },

  goToInventoryManage() {
    wx.navigateTo({
      url: '/pages/admin/inventory/inventory'
    })
  },

  goToOrderManage() {
    wx.navigateTo({
      url: '/pages/admin/orders/orders'
    })
  },

  goToReports() {
    wx.navigateTo({
      url: '/pages/admin/reports/reports'
    })
  },

  logout() {
    wx.showModal({
      title: '确认退出',
      content: '确定要退出管理后台吗？',
      success: (res) => {
        if (res.confirm) {
          app.logout()
          wx.showToast({
            title: '已退出登录',
            icon: 'success'
          })
          // 退出后跳转到登录页面
          setTimeout(() => {
            wx.redirectTo({
              url: '/pages/login/login'
            })
          }, 1500)
        }
      }
    })
  }
})